package com.hollycrm.hollysqm.analyzer.solr.auth;

import com.hollycrm.hollysqm.analyzer.util.ConfigUtil;
import com.hollycrm.hollysqm.analyzer.util.Constant;
import com.hollycrm.hollysqm.analyzer.util.JdbcCallback;
import com.hollycrm.hollysqm.analyzer.util.JdbcUtil;
import lombok.extern.log4j.Log4j;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by zhaihw on 2016/5/4.
 * solr鉴权类
 */
@Log4j
public enum SolrAuthentication {
    INSTANCE;
    /**
     * 可用ip集合
     */
    private static Set<String> ips = new HashSet<>();

    /**
     * 加载可以使用solr云的权限列表
     */
    public void loadAvailableIps() throws SQLException, ClassNotFoundException {
        log.info("flush solrCloud iptables ...");
        String authSql = ConfigUtil.getProp(Constant.authSql);
        Set<String> sets = JdbcUtil.INSTANCE.executeQuery(authSql, null, new JdbcCallback<Set<String>>() {
            @Override
            public Set<String> process(ResultSet rs) throws SQLException {
                Set<String> sets = new HashSet<>();
                while (rs.next()) {
                    String ip = rs.getString(1);
                    log.info(" * " + ip);
                    sets.add(ip);
                }
                return sets;
            }
        });
        ips.clear();
        ips.addAll(sets);
    }

    /**
     * 鉴权
     *
     * @param ip ip
     * @return 是否可用
     */
    public static boolean hasAuth(String ip) {
        return ips.contains(ip);
    }
}
